// ControlPanel.java
import java.util.Scanner;
import java.time.LocalDateTime;
import java.time.Duration;

public class ControlPanel {
    private State currentState;
    private String password = "1234"; // 设置的密码（实际中应从配置读取）
    private StringBuilder inputBuffer = new StringBuilder();
    private int errorCount = 0;
    private LocalDateTime lockTime = null;

    public ControlPanel() {
        this.currentState = new IdleState();
        System.out.println("控制面板启动，处于待机状态");
    }

    // 外部触发事件：敲击键盘按键
    public void pressKey(char key) {
        currentState.onKeyPress(this, key);
    }

    // 模拟定时检查是否超时解锁
    public void checkUnlock() {
        if (lockTime != null && Duration.between(lockTime, LocalDateTime.now()).getSeconds() >= 120) {
            System.out.println("锁定时间超过120秒，自动解锁");
            errorCount = 0;
            lockTime = null;
            currentState = new IdleState();
        }
    }

    // 获取当前输入的密码
    public String getCurrentInput() {
        return inputBuffer.toString();
    }

    // 清空输入缓冲区
    public void clearInput() {
        inputBuffer.setLength(0);
    }

    // 判断密码是否正确
    public boolean isPasswordCorrect() {
        return getCurrentInput().equals(password);
    }

    // 设置状态
    public void setState(State state) {
        this.currentState = state;
        System.out.println("状态切换为：" + state.getClass().getSimpleName());
    }

    // 获取错误次数
    public int getErrorCount() {
        return errorCount;
    }

    // 设置错误次数
    public void setErrorCount(int count) {
        this.errorCount = count;
    }

    // 设置锁定时间
    public void setLockTime(LocalDateTime time) {
        this.lockTime = time;
    }

    // 是否处于锁定状态
    public boolean isLocked() {
        return lockTime != null;
    }

    @Override
    public String toString() {
        return "ControlPanel{" +
                "currentState=" + currentState.getClass().getSimpleName() +
                ", input='" + inputBuffer + '\'' +
                ", errorCount=" + errorCount +
                ", lockTime=" + lockTime +
                '}';
    }

    // 主程序入口
    public static void main(String[] args) {
        ControlPanel panel = new ControlPanel();

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入密码（4位），按回车提交，输入 'quit' 退出");

        while (true) {
            String line = scanner.nextLine();
            if ("quit".equalsIgnoreCase(line)) break;

            for (char c : line.toCharArray()) {
                panel.pressKey(c);
            }

            // 每次输入后检查是否需要解锁
            panel.checkUnlock();
        }

        scanner.close();
    }
}